#! /usr/bin/env python

# Copyright (C) [2024] Xingyun Integrated Circuit Co., Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
# FIT FOR A PARTICULAR PURPOSE.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Project: GreenCode
# Created Date: 2025-09-17 20:11:49
# Author: Shawn Tan
# -----
# Last Modified: 2025-09-25 20:18:46
# Modified By: Shawn Tan
# -----
# May the force be with you.
# -----
# HISTORY:
# Date      	By	Comments
#                get the xml from isa spec json proc files 
# ----------------------------------------------------------------------

import logging
import argparse
import copy
import json
import os
import sys
from isa.groups import Group
from isa.optypes import Optype
from isa.opcodes import Opcode
import collections
          
class ISA_Parser(object):

  '''
    the isa parser to instrution list
  '''

  def __init__(self):

      super(ISA_Parser, self).__init__()

      parser = argparse.ArgumentParser(description='XINYUN ISG Parser Flow')
      parser.add_argument("-spec", action="store", default=None, dest='spec', \
                               help="set the spec")
      
      parser.add_argument("-i", action="store", default="./", dest='input_dir', \
                               help="set the spec dir")
      
      parser.add_argument("-o", action="store", default=None, dest='out_dir', \
                               help="set the spec")
      
      parser.add_argument("-split", action="store_true", default=False, dest='split', \
                               help="generate the instruction list per groups")
      self.args=parser.parse_args()
      assert self.args.spec !=None, "No Spec given"
      self.spec = "%s/%s"%(self.args.input_dir, self.args.spec)

      self.opcode_cnt = 0
      self.optype_cnt = 0
      self.group_cnt =0
      self.group_dict = collections.OrderedDict()

  def GetDataBase(self):

    assert os.path.isfile(self.spec), "%s not existed"%(self.spec)
    specfiles = open(self.spec, 'r')
    self.database = json.load(specfiles)

  def Parser(self):
     
      #print self.database.keys()
      #print len(self.database["OpGroups"].keys())
      #print self.database["OpGroups"].keys()
      optype_cnt = 0
      opcode_cnt = 0
      group_cnt = 0
      group_dict = {}
      for name in self.database["OpGroups"].keys():
        if self.database["OpGroups"][name]['type'] == 'Optype':
          optype_cnt += 1
          #print "key name %s; name %s type %s"%(name, self.database["OpGroups"][name]['name'], self.database["OpGroups"][name]['type'])

          #inherit = self.database["OpGroups"][name]["metadata"]['inherit']
          #print inherit
          
        elif self.database["OpGroups"][name]['type'] == 'Group':
          group_cnt += 1
          #print "key name %s; name %s type %s"%(name, self.database["OpGroups"][name]['name'], self.database["OpGroups"][name]['type'])
          inherit = self.database["OpGroups"][name]["metadata"]['inherit']
          name = self.database["OpGroups"][name]['name']
          #print inherit

        elif self.database["OpGroups"][name]['type'] == 'Opcode':
          opcode_cnt += 1
          #print "key name %s; name %s type %s"%(name, self.database["OpGroups"][name]['name'], self.database["OpGroups"][name]['type'])
    
      print "group cnt is %s"%(group_cnt)
      print "optype_cnt is %s"%(optype_cnt)
      print "opcode_cnt is %s"%(opcode_cnt)
      
      group_list = []
      while(group_cnt): 
        for name in self.database["OpGroups"].keys():
           if self.database["OpGroups"][name]['type'] == 'Group':
              inherit = self.database["OpGroups"][name]["metadata"]['inherit']
              _name = self.database["OpGroups"][name]['name']

              assert name == _name

              if name not in group_list:

                if len(inherit):
                  index = inherit[0]
                  if index in group_dict.keys():
                    group_dict[index][name] = {} 
                    group_cnt -= 1
                    group_list.append(name)
                  else:
                    for g1 in group_dict.keys():
                      if index in group_dict[g1].keys():
                        group_dict[g1][index][name] = {} 
                        group_cnt -= 1
                        group_list.append(name)
                      else:
                        for g2 in group_dict[g1].keys():
                          if index in group_dict[g1][g2].keys():
                            group_dict[g1][g2][index][name] = {} 
                            group_cnt -= 1
                            group_list.append(name)
                elif len(inherit) == 0:
                    group_dict[name] = {} 
                    group_cnt -= 1
                    group_list.append(name)

      for i in group_dict.keys():
        print"%s:"%(i)
        if len(group_dict[i].keys()):
          for j in group_dict[i].keys():
              print"--%s:"%(j)
              if len(group_dict[i][j].keys()):
                for k in group_dict[i][j].keys():
                     print"----%s:"%(k)

  def Render(self):
    pass

  def Run(self):

    self.GetDataBase()
    self.Parser()
    self.Render()

if __name__ == "__main__":
   parser = ISA_Parser()
   parser.Run()